import React from 'react';
import { Link } from 'react-router';
import { Breadcrumb, Row, Col, Input, DatePicker, Select, Button, Table, Modal, Pagination, message, Popconfirm, Form, Cascader } from 'antd';
import moment from 'moment';
import $ from 'jquery';
import Config from '../../common/config';
import '../../common/common.less';

const FormItem = Form.Item;
const Textarea = Input.TextArea;
const Option = Select.Option;
const config = new Config();

class diseaseManage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      cgtData: [
        {
          id: '1',
          first_classify: '1-1',
          second_classify: '2-1',
          coding_classify: '1324',
          associated_states: 0,
        },
        {
          id: '1',
          first_classify: '1-1',
          second_classify: '2-1',
          coding_classify: '1324',
          associated_states: 1,
        }
      ], //病症表格数据
      title: '', //疾病名称
      behavior: '',//症状表现
      status: 0,  //0全部 1未发布 2已发布
      page: 1,
      pageSize: 10,
      total: null,
      addModal: false,//添加模态框
      categoryCheck: [], //二级联动check类目
      options: [{
        value: 'zhejiang111111111',
        label: 'Zhejiang111111111',
        children: [{
          value: 'hangzhou',
          label: 'Hangzhou',
          children: [{
            value: 'xihu',
            label: 'West Lake',
          }],
        }],
      }, {
        value: 'jiangsu',
        label: 'Jiangsu',
        children: [{
          value: 'nanjing',
          label: 'Nanjing',
          children: [{
            value: 'zhonghuamen',
            label: 'Zhong Hua Men',
          }, {
            value: 'ceshi',
            label: 'ceshi'
          }],
        }],
      }],
      categoryList: [],
      isNew: true,   //是否是新增
      changeId: '',  //被修改的类目id
      classify: '', //输入的类目名
      associated_states: 'all',//选择的关联状态
      coding_classify: '' //输入的类目编码

    }
    this.selectChange = this.selectChange.bind(this)
  }

  componentDidMount() {
    this.initData();
  }

  // 获取初始数据
  initData() {
    $.ajax({
      url: `${config.healthAftercare}/healthplatform/category`,
      type: 'get',
      data: {
        pagesize: this.state.pageSize,
        pageindex: this.state.page,
        first_classify: this.state.classify[0],
        second_classify: this.state.classify[1],
        associated_states: this.state.associated_states,
        coding_classify: this.state.coding_classify
      },
      headers: {
        'Authorization': 'Bearer ' + sessionStorage.getItem('token'),
      },
      success: res => {
        console.log(res)
        if (res.code === 200) {
          console.log(res.data.rows)
          this.setState({
            categoryList: res.data.rows
          })
          console.log(res.category, '后端处理后的数据')

          let initcat = res.category;
          let categoryCheck = [];
          for (let i in initcat) {
            console.log(i, initcat[i])
            let checkitem = {};
            checkitem.value = i;
            checkitem.label = i;
            let itemlist = []
            initcat[i].map((val) => {
              itemlist.push({ value: val.second_classify, label: val.second_classify })
            })
            checkitem.children = itemlist
            categoryCheck.push(checkitem)
          }
          console.log(categoryCheck, 'categoryCheck')
          this.setState({
            categoryCheck,
            total: res.data.count
          })

        }else{
          message.error('错误')
        }
      }
    })
  }
  //选择搜索条件
  selectChange(tip, e) {
    console.log(tip, e)
    if (tip == 1) {
      this.setState({
        classify: e
      })
    } else if (tip == 3) {
      this.setState({
        associated_states: e
      })
    } else {

    }
  }
  Inputcode(e) {
    console.log(e.target.value)
    this.setState({
      coding_classify: e.target.value
    })
  }

  // 搜索/清空
  filterOrders(key) {
    if (key) {
      // 搜索
      this.setState({
        page: 1
      }, () => {
        this.initData();
      });
    } else {
      // 清空
      this.setState({
        page: 1,
        associated_states: 'all',
        coding_classify: '',
        classify: []
      }, () => {
        this.initData();
      });
    }
  }
  // 删除
  deleteCtg(record) {
    console.log(record)
    $.ajax({
      url: `${config.healthAftercare}/healthplatform/category`,
      type: 'delete',
      data: {
        id: record.id
      },
      headers: {
        'Authorization': 'Bearer ' + sessionStorage.getItem('token'),
      },
      success: res => {
        console.log(res)
        if (res.code === 200) {
          message.success(res.mes)
          this.initData()
        } else {
          message.error(res.mes)
        }
      },
      error: res => {
        console.log(res)
      }

    })
  }

  // 切换分页
  onChangePage(page) {
    this.setState({
      page
    }, () => {
      this.initData();
    });
  }

  // 表格
  getColumns() {
    return [{
      title: '序号',
      width: '5%',
      dataIndex: 'id'
    }, {
      title: '一级类目',
      width: '15%',
      dataIndex: 'first_classify'
    }, {
      title: '二级类目',
      width: '15%',
      dataIndex: 'second_classify'
    }, {
      title: '类目编码',
      width: '15%',
      dataIndex: 'coding_classify'
    }, {
      title: '关联状态',
      width: '15%',
      render: (text, record) => (
        <p>{record.associated_states == 1 ? '是' : '否'}</p>
      )
    }, {
      title: '操作',
      width: '20%',
      dataIndex: 'caozuo',
      render: (text, record) => (
        <div>
          <Button type="primary" onClick={this.showModal.bind(this, record)} >编辑</Button>&nbsp;&nbsp;
           
           <Popconfirm title="您确定要删除么？" okText="是" cancelText="否" onConfirm={this.deleteCtg.bind(this, record)}>
           <Button type="danger"  style={record.associated_states == 0 ? { display: "inline" } : { display: "none" }}>删除</Button>&nbsp;&nbsp;
            </Popconfirm>
        </div>
      )
    }]
  }

  // 保存
  save(e) {
    this.props.form.validateFields((err, values) => {
      console.log(err, values, '提交')

      if (!err) {
        console.log('成功')
        let data = {
          second_classify: values.second_classify
        }
        if (values.first_classify_new) {
          data.first_classify = values.first_classify_new
        } else {
          data.first_classify = values.first_classify
        }

        let msg = '', method = '';


        if (this.state.isNew === false) {
          console.log('修改')
          data.id = this.state.changeId
          msg = '修改成功'
          method = 'put'
        } else {
          msg = '新增成功'
          method = 'post'
        }
        console.log(data)
        $.ajax({
          url: `${config.healthAftercare}/healthplatform/category`,
          method,
          data,
          headers: {
            'Authorization': 'Bearer ' + sessionStorage.getItem('token'),
          },
          success: res => {
            console.log(res)
            if (res.code == 200) {
              message.success(msg)
              this.setState({
                addModal: false
              })
              this.props.form.resetFields();
              this.initData()
            } else {
              message.error(res.mes)
            }
          }
        })
      }
    })
  }



  // 显示模态框
  showModal(value) {
    console.log('是否是编辑', value)
    if (value) {//编辑
      this.setState({
        isNew: false,
        addModal: true,
        changeId: value.id
      }, () => {
        this.props.form.setFieldsValue({
          first_classify: value.first_classify,
          second_classify: value.second_classify
        })
      })
    } else {
      this.setState({
        isNew: true,
        addModal: true
      })
    }

  }

  //取消，关闭对话框
  handleCancel() {
    this.props.form.resetFields();
    this.setState({
      addModal: false,
    });
  }

  render() {
    const columns = this.getColumns();
    const formItemLayout = { labelCol: { span: 4 }, wrapperCol: { span: 20 } };
    const { getFieldDecorator } = this.props.form;
    const { categoryCheck } = this.state;
    return (
      <div className='goods-label clerafix'>
        < Breadcrumb separator=">" >
          <Breadcrumb.Item>健康调养</Breadcrumb.Item>
          <Breadcrumb.Item>类目管理</Breadcrumb.Item>
        </Breadcrumb >
        <div style={{ marginTop: '20px' }}>
          <div className="member-content-Search" style={{ marginBottom: 20 }}>

            {/* <Input addonBefore='疾病名称' placeholder="请输入"  onChange={this.InputSearch.bind(this,0)} /> */}
            <Row type="flex" justify="space-between">
              <Col span={5}>
                <span>类目&nbsp;&nbsp;</span><Cascader options={categoryCheck} value={this.state.classify} onChange={this.selectChange.bind(this, 1)} placeholder="请选择类目" />
              </Col>
              <Col span={5}>
                <Input addonBefore='类目编码' placeholder="请输入类目编码" value={this.state.coding_classify} onChange={this.Inputcode.bind(this)} />
              </Col>
              <Col span={5}>
                <span>关联状态:&nbsp;&nbsp;&nbsp;&nbsp;</span>
                <Select value={this.state.associated_states} onChange={this.selectChange.bind(this, 3)} style={{ width: '80px' }}>
                  <Option value="all">全部</Option>
                  <Option value="1">是</Option>
                  <Option value="0" >否</Option>
                </Select>
              </Col>
              <Col span={5}>
                <Button className='ant-btn-primary' icon='search' onClick={this.filterOrders.bind(this, 1)}>搜索</Button>
                <Button className='ant-btn-primary' icon='sync' onClick={this.filterOrders.bind(this, 0)}>重置</Button>
              </Col>
            </Row>
          </div>
        </div>
        <div>
          <Button className='ant-btn-primary' onClick={this.showModal.bind(this, false)}>新增类目</Button>
        </div>
        <div style={{ marginTop: '20px' }}>
          <Table columns={columns} dataSource={this.state.categoryList} pagination={false} bordered rowKey='id' />
        </div>
        <div className='goods-label-let clearfix'>
          <div className="floor-ppagi">
            {
              this.state.total == 0 ?
                <p className="floor-ppagip">
                  共{this.state.total}条记录
              </p> :
                <p className="floor-ppagip">
                  当前显示
                {this.state.pageSize * (this.state.page - 1) + 1}—
                {this.state.pageSize * this.state.page < this.state.total ? this.state.pageSize * this.state.page : this.state.total}条记录，
                共{this.state.total}条记录
              </p>
            }
            <Pagination current={this.state.page} total={this.state.total || 1} defaultPageSize={this.state.pageSize} onChange={this.onChangePage.bind(this)} />
          </div>
        </div>
        <Modal
          title={this.state.isNew === true ? '新增类目' : '修改'}
          visible={this.state.addModal}
          okText={this.state.isNew === true ? '新增' : '修改'}
          cancelText='取消'
          onCancel={this.handleCancel.bind(this)}
          onOk={this.save.bind(this)}
        >
          <Form >
            <FormItem
              label='一级类目'
              {...formItemLayout}
            >
              {getFieldDecorator('first_classify', {
                // rules:[{
                //   required:true,message:'限15字内（必填项）',
                //   max:15,message:'限15字内',
                // }]
              })(
                <Select>
                  {
                    this.state.categoryCheck.map((val, index) => {
                      return <Option value={val.value}>{val.value}</Option>
                    })
                  }
                  {/* <Option value="jack">全部</Option>
                <Option value="lucy">是</Option>
                <Option value="disabled" >否</Option> */}
                </Select>
              )}
            </FormItem>
            <FormItem
              label='&nbsp;&nbsp;&nbsp;&nbsp;'
              {...formItemLayout}
            >
              {getFieldDecorator('first_classify_new', {
                rules: [
                  { max: 15, message: '限15字内' }
                ]
              })(
                <Input placeholder='或输入新增一级类目名称' />
              )}
            </FormItem>
            <FormItem
              label='二级类目'
              {...formItemLayout}
            >
              {getFieldDecorator('second_classify', {
                rules: [
                  { required: true, message: '输入二级类目名称' },
                  { max: 15, message: '限15字内', }
                ]
              })(
                <Input type='title' placeholder='输入二级类目名称' />
              )}

            </FormItem>
          </Form>
        </Modal>
      </div>

    )
  }
}


export default Form.create()(diseaseManage);